package com.hack.validator;


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * 数据库管理类
 * 包含数据库初始化和获取连接方法
 *
 * @author hack
 * @version 1.0
 * @date 2025/07/11
 */
public class DBManager {
    private static final String DB_URL = "jdbc:h2:file:./config/param_validator;DB_CLOSE_DELAY=-1;AUTO_SERVER=TRUE";
    private static final String DB_USER = "sa";
    private static final String DB_PASS = "";

    public static void initDatabase() {
        try (Connection conn = getConnection();
             Statement stmt = conn.createStatement()) {

            // 创建规则表
            stmt.execute("CREATE TABLE IF NOT EXISTS validation_rules (" +
                    "id INT AUTO_INCREMENT PRIMARY KEY," +
                    "param_path VARCHAR(255) NOT NULL," +
                    "param_type VARCHAR(50) NOT NULL," +
                    "rule_type VARCHAR(50) NOT NULL," +
                    "rule_config VARCHAR(255)," +
                    "error_msg VARCHAR(255) NOT NULL," +
                    "app_id VARCHAR(50) NOT NULL," +
                    "UNIQUE (param_path, rule_type, app_id))");

            // 创建索引
            stmt.execute("CREATE INDEX IF NOT EXISTS idx_app_id ON validation_rules(app_id)");

        } catch (SQLException e) {
            throw new RuntimeException("Database initialization failed", e);
        }
    }

    public static Connection getConnection() throws SQLException {
        return DriverManager.getConnection(DB_URL, DB_USER, DB_PASS);
    }
}